package com.xiaoshuidi.cloud.module.rooms.mq.consumer;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONUtil;
import com.xiaoshuidi.cloud.framework.common.util.json.JsonUtils;
import com.xiaoshuidi.cloud.framework.tenant.core.util.TenantUtils;
import com.xiaoshuidi.cloud.module.finance.enums.finance.SourceBizTypeEnum;
import com.xiaoshuidi.cloud.module.finance.mq.PayResultConstants;
import com.xiaoshuidi.cloud.module.finance.mq.message.PayResultMessage;
import com.xiaoshuidi.cloud.module.rooms.service.IRoomHouseReserveService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.function.Consumer;

/**
 * 支付结果通知
 */
@Slf4j
@Component(PayResultConstants.CONSUMER)
@RequiredArgsConstructor
public class PayResultConsumer implements Consumer<String> {
    private final IRoomHouseReserveService reserveService;

    @Override
    public void accept(String payResultMessage) {
        log.info("预定或退定收款：" + JSONUtil.toJsonStr(payResultMessage));
        PayResultMessage bean = JsonUtils.parseObject(payResultMessage, PayResultMessage.class);
        if (SourceBizTypeEnum.ROOM_RESERVE.name().equals(bean.getSourceBizType())) {
            TenantUtils.execute(bean.getTenantId(), () -> {
                if (bean.getSuccess()) {
                    Date payTime = bean.getPayTime();
                    LocalDateTime payTimeL = LocalDateTimeUtil.of(payTime);
                    reserveService.paymentSuccessful(Long.valueOf(bean.getSourceBizId()), bean.getFlowId(), payTimeL,bean.getPayMethod());
                }
            });
        }
        if (SourceBizTypeEnum.RESERVE_WITHDRAW.name().equals(bean.getSourceBizType())) {
            TenantUtils.execute(bean.getTenantId(), () -> {
                if (bean.getSuccess()) {
                    Date payTime = bean.getPayTime();
                    LocalDateTime payTimeL = LocalDateTimeUtil.of(payTime);
                    reserveService.withdrawPaymentSuccessful(Long.valueOf(bean.getSourceBizId()), bean.getFlowId(), payTimeL);
                }
            });
        }
    }
}
